﻿using MediatR;
using SupplyChain.Domain.Entities;
using SupplyChain.Infrastructure.Interface;
using SupplyChain.Write.API.Application.Command.PurchaseOrder;

namespace SupplyChain.Write.API.Application.CommandHandler.PurchaseOrder
{
    public class DelPurchaseOrderHandler : IRequestHandler<DelPurchaseOrderCommand, bool>
    {
        private readonly IBaseRepository<Domain.Entities.PurchaseOrder> repository;
        private readonly IBaseRepository<PurchaseOrderDetail> detailRep;

        public DelPurchaseOrderHandler(IBaseRepository<Domain.Entities.PurchaseOrder> repository, IBaseRepository<PurchaseOrderDetail> detailRep)
        {
            this.repository = repository;
            this.detailRep = detailRep;
        }

        public async Task<bool> Handle(DelPurchaseOrderCommand request, CancellationToken cancellationToken)
        {
            if (request.Id <= 0) return await Task.FromResult(false);

            Domain.Entities.PurchaseOrder order = await repository.GetByPrimaryKeyAsync(request.Id);
            List<PurchaseOrderDetail> detail = await detailRep.GetByWhereAsync(x => x.PuId.Equals(request.Id));
            order.IsDel = !order.IsDel;
            if (detail != null && detail.Count > 0)
            {
                foreach (PurchaseOrderDetail detailItem in detail)
                {
                    detailItem.IsDel = !detailItem.IsDel;
                }
                await detailRep.UpdateRangeAsync(detail);
            }
            return await Task.FromResult(await repository.UpdateAsync(order));
        }
    }
}
